package com.yy.permissions_general.security.handler;

import com.yy.permissions_general.common.constant.SystemConstant;
import com.yy.permissions_general.module.system.menu.vo.MenuVo;
import com.yy.permissions_general.module.system.user.entity.User;
import com.yy.permissions_general.utils.FastJsonUtils;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @program: permissions_general
 * @description: 自定义权限认证 hasPermission
 * @author: YY
 * @create: 2021-11-29 22:34
 **/
@Component
public class UserPermissionEvaluator implements PermissionEvaluator {

    /**
     * hasPermission鉴权方法
     * @Param  permission 请求按钮的权限
     * @Return boolean 是否通过
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object targetUrl, Object permission) {
        User user = FastJsonUtils.toBean(authentication.getPrincipal(),User.class);
        if (SystemConstant.SUPER_AUTH_OPEN && SystemConstant.SUPER_ADMIN.equals(user.getAccount())) {
            return true;
        }
        List<MenuVo> menuVoList = user.getMenuVoList();
        Set<String> permissions = new HashSet<>();
        for (MenuVo menuVo : menuVoList) {
            permissions.add(menuVo.getAuthCode());
        }
        return permissions.contains(permission);
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
